package com.note.chh.notebook.Uitls;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.note.chh.notebook.Model.WeatherBean;
import com.note.chh.notebook.MyApplication;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by caihuahui on 2018/3/6.
 */

public class WeatherUtils {
    private static WeatherUtils instance;

    private Map<String, WeatherBean> weatherBeanMap;

    private WeatherUtils() {
        weatherBeanMap = new HashMap<>();
        List<WeatherBean> list = new Gson().fromJson(readFromAssets(),
                new TypeToken<List<WeatherBean>>() {
                }.getType());
        for (WeatherBean bean : list) {
            weatherBeanMap.put(bean.getCode(), bean);
        }
    }

    public static WeatherUtils getInstance() {
        if (instance == null) {
            synchronized (WeatherUtils.class) {
                instance = new WeatherUtils();
            }
        }
        return instance;
    }

    public String getUrl(String code){
        String url = "";
        if (WeatherUtils.getInstance().weatherBeanMap.containsKey(code)) {
            WeatherBean weatherBean = WeatherUtils.getInstance().weatherBeanMap.get(code);
            url = weatherBean.getIcon();
        }else{
            WeatherBean weatherBean = WeatherUtils.getInstance().weatherBeanMap.get("999");
            url = weatherBean.getIcon();
        }

        return url;
    }

    private String readFromAssets() {
        try {
            InputStream is = MyApplication.instance.getAssets().open("weather_map.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            return new String(buffer, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
